package org.wannatrak.android.helper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.TypedValue;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;
import org.wannatrak.android.ApplicationContext;
import org.wannatrak.android.entity.Dimension;
import org.wannatrak.android.intf.ClickAction;
import org.wannatrak.android.intf.DatatypeConstants;
import org.wannatrak.android.intf.DialogAction;
import org.wannatrak.android.intf.ItemClickAction;

import java.util.Date;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-06-27 11:07:23 +0000 (Mon, 27 Jun 2011) $ 2:53:12 PM
 * @version: $Revision: 22 $
 * @id: $Id: UIHelper.java 22 2011-06-27 11:07:23Z maxtulupov@gmail.com $
 */
public class UIHelper {

    public final static int ON_CLICK = 0;

    public final static int ON_LONG_CLICK = 1;

    public final static int ON_ITEM_SELECT = 2;

    public static void setActionToView(Spinner spinner,
                                       final ItemClickAction clickAction) {
        spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> adapterView, View view,
                                       int i, long l) {
                clickAction.onItemSelect(adapterView, view, i, l);
            }

            public void onNothingSelected(AdapterView<?> adapterView) {
                clickAction.onNothingSelected(adapterView);
            }
        });
    }

    public static void setActionToView(View view, final ClickAction clickAction) {
        setActionToView(view, clickAction, ON_CLICK);
    }

    public static void setActionToView(View view,
                                       final ClickAction clickAction, int type) {
        switch (type) {
            case ON_CLICK:
                view.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                        clickAction.actionPerformed(view);
                    }
                });
                break;
            case ON_LONG_CLICK:
                view.setOnLongClickListener(new View.OnLongClickListener() {

                    public boolean onLongClick(View view) {
                        return clickAction.actionPerformed(view);
                    }
                });
                break;
            default:
                throw new IllegalArgumentException("unknown type " + type);
        }
    }

    public static void setActionToView(AdapterView view,
                                       final ItemClickAction clickAction, int type) {
        switch (type) {
            case ON_CLICK:
                view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> adapterView, View view,
                                            int i, long l) {
                        clickAction.onItemSelect(adapterView, view, i, l);
                    }
                });
                break;
            case ON_LONG_CLICK:
                view.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

                    public boolean onItemLongClick(AdapterView<?> adapterView,
                                                   View view, int i, long l) {
                        return clickAction.onItemSelect(adapterView, view, i, l);
                    }
                });
                break;
            case ON_ITEM_SELECT:
                view.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> adapterView,
                                               View view, int i, long l) {
                        clickAction.onItemSelect(adapterView, view, i, l);
                    }

                    public void onNothingSelected(AdapterView<?> adapterView) {
                        clickAction.onNothingSelected(adapterView);
                    }
                });
                break;
            default:
                throw new IllegalArgumentException("unknown type " + type);
        }
    }

    public static int getDrawableIdentifier(final Context context, final String key) {
        return context.getResources().getIdentifier(key, "drawable", ApplicationContext.AUTHORITY);
    }

    public static Dimension getScreenSize(Activity activity) {
        Display display = activity.getWindowManager().getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();
        return new Dimension(width, height);
    }

    public static void setValuesFromCursor(Activity activity, Cursor cursor,
                                           int[] components, String[] fields, int[] datatypes) {
        int length = components.length;
        if (length != fields.length || length != datatypes.length) {
            throw new IllegalArgumentException("array sizes mismatch");
        }
        for (int i = 0; i < length; i++) {
            TextView textView = (TextView) activity.findViewById(components[i]);
            String field = fields[i];
            Object value = getCursorValue(cursor, field, datatypes[i]);
            textView.setText(String.valueOf(value));
        }
    }

    public static float pixelsToDip(View view, float pixels) {
        return convertMeasure(view, pixels, TypedValue.COMPLEX_UNIT_DIP);
    }

    public static int dipToPixels(View view, float pixels) {
        return convertMeasure(view, pixels, TypedValue.COMPLEX_UNIT_PX);
    }

    public static int dipToPixels(View view, int pixelsId) {
        return convertMeasure(view, view.getResources().getDimension(pixelsId),
                TypedValue.COMPLEX_UNIT_PX);
    }

    public static Dialog createAlertDialog(Context context, String message, int view,
                                           boolean cancellable, final DialogAction[] actions) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setInverseBackgroundForced(true);
        if (view > 0) {
            LayoutInflater layoutInflater =
                    (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = layoutInflater.inflate(view, null);
            builder.setView(v);
        }
        if (message != null) {
            builder.setMessage(message);
        }
        builder.setCancelable(cancellable);
        if (actions != null) {
            switch (actions.length) {
                case 3: {
                    builder.setNeutralButton(actions[2].getNameCode(),
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialogInterface, int i) {
                                    actions[2].actionPerformed(dialogInterface, i);
                                }
                            });
                }
                case 2: {
                    builder.setNegativeButton(actions[1].getNameCode(),
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialogInterface, int i) {
                                    actions[1].actionPerformed(dialogInterface, i);
                                }
                            });
                }
                case 1: {
                    builder.setPositiveButton(actions[0].getNameCode(),
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialogInterface, int i) {
                                    actions[0].actionPerformed(dialogInterface, i);
                                }
                            });
                }
            }
        } else {
            builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                }
            });
        }
        return builder.create();
    }

    public static Dialog createAlertDialog(Context context, int messageCode, int view,
                                           boolean cancellable, final DialogAction[] actions) {
        String message = null;
        if (messageCode > 0) {
            message = context.getResources().getString(messageCode);
        }
        return createAlertDialog(context, message, view, cancellable, actions);
    }


    public static Dialog createAlertDialog(Context context, int messageCode,
                                           boolean cancellable, final DialogAction[] actions) {
        return createAlertDialog(context, messageCode, -1, cancellable, actions);
    }

    public static Dialog createAlertDialog(Context context, int messageCode,
                                           boolean cancellable, final DialogAction action) {
        return createAlertDialog(context, messageCode, cancellable,
                new DialogAction[]{action});
    }

    public static Object getCursorValue(Cursor cursor, String name, int type) {
        switch (type) {
            case DatatypeConstants.BLOB:
                return cursor.getBlob(cursor.getColumnIndex(name));
            case DatatypeConstants.BYTE:
                return cursor.getShort(cursor.getColumnIndex(name));
            case DatatypeConstants.DOUBLE:
                return cursor.getDouble(cursor.getColumnIndex(name));
            case DatatypeConstants.FLOAT:
                return cursor.getFloat(cursor.getColumnIndex(name));
            case DatatypeConstants.INT:
                return cursor.getInt(cursor.getColumnIndex(name));
            case DatatypeConstants.LONG:
                return cursor.getLong(cursor.getColumnIndex(name));
            case DatatypeConstants.STRING:
                return cursor.getString(cursor.getColumnIndex(name));
            case DatatypeConstants.DATE:
                return new Date(cursor.getLong(cursor.getColumnIndex(name)));
            case DatatypeConstants.BOOLEAN:
                int anInt = cursor.getInt(cursor.getColumnIndex(name));
                return anInt == 0 ? Boolean.FALSE : Boolean.TRUE;
            default:
                throw new IllegalArgumentException("unknown datatype " + type);

        }
    }

    private static int convertMeasure(View view, float value, int type) {
        Resources resources = view.getResources();
        return (int) TypedValue.applyDimension(type, value,
                resources.getDisplayMetrics());
    }

    public static boolean isGpsEnabled(Context context) {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    public static boolean isOnline(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo netInfo = cm.getActiveNetworkInfo();

        return netInfo != null && netInfo.isConnectedOrConnecting();
    }

    public static void closeSoftInput(Activity activity) {
        final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }
}
